<!--回收入库-->
<template>
  <!-- 添加或修改对话框 -->
  <el-dialog :title="t" :visible.sync="show" width="990px" append-to-body :close-on-click-modal="false"
             class="dialog-wrapper">

    <!--dilog内容-->
    <div class="dialog-con">
      <el-form ref="form" :model="form" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="游戏品类" prop="dictCodeId">
              <el-select v-model="form.dictCodeId" placeholder="请选择游戏品类" @change="handleGameChange">
                <el-option v-for="item in gameList" :key="item.dictCode" :label="item.dictLabel"
                           :value="item.dictCode"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="回收渠道" prop="recycleChannelId">
              <el-select v-model="form.recycleChannelId" placeholder="请选择回收渠道">
                <el-option v-for="  item   in   recycleChannelList  " :key="item.dictCode" :label="item.dictLabel"
                           :value="item.dictCode + ''"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="回收编号" prop="orderNumber">
              <el-input v-model="form.orderNumber" placeholder="请输入回收编号"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="账号" prop="account">
              <el-input v-model="form.account" placeholder="请输入账号"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="区服" prop="region">
              <el-select filterable v-model="form.region" placeholder="请选择区服">
                <el-option v-for="item in regionalServers" :key="item.id" :label="item.gameField"
                           :value="item.gameField"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="账号描述" prop="accountDescription">
              <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 5 }" v-model="form.accountDescription"
                        placeholder="请输入账号描述"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="回收金额" prop="recycleAmount">
              <el-input v-if="form.recycleAmount" v-model="form.recycleAmount" placeholder="请输入回收金额"/>
              <el-input v-else v-model="form.suAmount " placeholder="请输入回收金额"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="销售金额" prop="saleAmount">
              <el-input v-model="form.saleAmount" placeholder="请输入销售金额"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="绑定类目" prop="bindingChannelId">
              <el-select @change="changeChannel" v-model="form.bindingChannelId" placeholder="请选择绑定类目">
                <el-option v-for="item in bindingChannelList" :key="item.dictCode" :label="item.dictLabel"
                           :value="item.dictCode"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="选择手机" prop="phoneId">
              <div style="display: flex; align-items: center;">
                <el-select @change="changePhone" filterable v-model="form.phoneId" placeholder="请选择绑定手机">
                  <el-option v-for="item in phoneList" :key="item.phoneId" :label="item.phoneNumber"
                             :value="item.phoneId"/>
                </el-select>
                <el-button type="info" icon="el-icon-copy-document" @click="copyPhone"
                           style="color:#fff;margin-left: 10px;background: linear-gradient(268.09deg, #6067fa 0%, #7799fc 100%);"></el-button>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="手机编号" prop="phoneCode">
              <el-input disabled v-model="form.phoneCode" placeholder="请先选择手机编号"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="换绑客服" prop="changeId">
              <el-select v-model="form.changeId" placeholder="请选择换绑客服">
                <el-option v-for=" item in changeList" :key="item.userId" :label="item.userName"
                           :value="item.userId"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="回收客服" prop="recycleId"
                          :rules="{required:true,message:'回收客服不能为空！',trigger: 'change'}">
              <el-select v-model="form.recycleId" placeholder="请选择回收客服">
                <el-option v-for="(item,indx) in recycleList" :key="indx" :label="item.userName" :value="item.userId"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 5 }" v-model="form.remark"
                        placeholder="请输入备注"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="上传图片">
              <el-row>
                <el-col :span="3" v-for="(item,indx) in form.imagess" :key="indx" style="margin-bottom:10px;">
                  <div class="show-img">
                    <i class="el-icon-error icon" @click="handleDel(indx)"/>
                    <el-image style="width:100%;height:100%;" :src="item" :preview-src-list="form.imagess"/>
                  </div>
                </el-col>

                <el-col :span="3">
                  <div class="wrap_img">
                    <el-upload :action="imgUrl + '/common/upload'" :show-file-list="false" multiple
                               :on-success="handleSuccess" :before-upload="beforeAvatarUpload">
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>

        <p v-if="form.dictCodeId">属性信息</p>
        <div v-for="(child,ii) in result" :key="child.id" class="render" v-if="form.dictCodeId">
          <!--下拉框-->
          <el-form-item v-if="child.fieldType === 'select' && child && child.children && child.children.length > 0"
                        :label="child.gameField" :prop="'dropDown_'+child.id"
                        :rules="{required: child.isRequired==1?true:false,message:child.gameField + '不能为空',trigger:'change'}">
            <el-select :disabled="disabled" v-model="form['dropDown_'+child.id]">
              <el-option v-for="(item,indx) in child.children" :key="indx" :label="item.gameField"
                         :value="parseInt(item.id)"/>
            </el-select>
          </el-form-item>

          <!--输入框-->
          <div style="display: flex; flex-wrap: wrap; gap: 10px;"
               v-if="child && child.fieldType === 'input' && child.children && child.children.length > 0">
            <el-form-item v-for="item in child.children" :key="item.id" :label="item.gameField"
                          :prop="'inputValues_'+item.id"
                          :rules="{required: child.isRequired==1?true:false,message:item.gameField + '不能为空',trigger:'blur'}">
              <el-input :disabled="disabled" placeholder="请输入" v-model="form['inputValues_' + item.id]"></el-input>
            </el-form-item>
          </div>

          <!--radio 单选框-->
          <el-form-item v-if="child.fieldType === 'radio' && child && child.children && child.children.length > 0"
                        :label="child.gameField" :prop="'radioValues_'+child.id"
                        :rules="{required: child.isRequired==1?true:false,message:child.gameField +'不能为空',trigger:'change'}">
            <el-radio-group :disabled="disabled" v-model="form['radioValues_'+child.id]">
              <el-radio v-for="option in child.children" :key="option.id" :label="option.id">
                {{ option.gameField }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <!--checkbox 多选框-->
          <el-form-item v-if="child.fieldType === 'checkbox' && child && child.children && child.children.length > 0"
                        :label="child.gameField" :prop="'checkbox_' + child.gameKey"
                        :rules="[{ type: 'array', required: child.isRequired==1?true:false, message: '请至少选择一个' + child.gameField, trigger: 'change' }]">
            <el-checkbox-group v-model="form['checkbox_' + child.gameKey]"
                               v-if="child.gameKey && form['checkbox_' + child.gameKey]">
              <el-checkbox :disabled="disabled" v-for="item in child.children" :key="item.id" :label="item.id">
                {{ item.gameField }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!--底部按钮-->
    <div slot="footer" class="dialog-footer">
      <el-button class="cancel" @click="handleClose">取 消</el-button>
      <el-button class="confirm" type="primary" @click="handleConfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {listDict} from '@/api/business/gameDict.js';
import {
  unboundPhonesByCategory,
} from '@/api/business/staylnventory';
import env from "@/utils/config.js";
import {recycleAndStorage} from "@/api/business/customer.js";

export default {
  name: 'recycle',
  data() {
    return {
      disabled: false,
      imgUrl: '',
      show: false,
      t: '',//标题
      form: {},//表单
      bindingChannelId: '',
      gameList: [],//游戏种类
      recycleChannelList: [],//回收渠道
      regionalServers: [],//区域服务
      bindingChannelList: [],//绑定渠道
      phoneList: [],//绑定手机
      changeList: [],//换绑客服
      recycleList: [],//回收客服
      phoneData: {
        phoneCode: null,
        phoneId: null,
        phoneNumber: null
      },
      result: []
    }
  },
  methods: {
    // 删除照片
    handleDel(indx) {
      this.form.imagess.splice(indx, 1);
    },

    // 后边添加上传图片
    handleSuccess(res, file, fileList) {
      this.form.imagess.push(res.url);
    },

    // 上传图片判断
    beforeAvatarUpload(file) {
      const isJPEG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const jsJPG = file.type === 'image/jpg'
      if (!isJPEG && !isPNG && !jsJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        return false
      }
      return true;
    },

    // 确认提交信息
    handleConfirm() {
      let dropDownMap = {}, inputValuesObj = {}, radioSelectionsObj = {}, info = {}, checkboxArr = [];
      for (var key in this.form) {
        // 下拉框
        if (key.indexOf('dropDown') > -1) {
          dropDownMap[key.split('_')[1]] = this.form[key];
        }

        // 输入框
        if (key.indexOf('inputValues') > -1) {
          inputValuesObj[key.split('_')[1]] = this.form[key]
        }

        // 单选框
        if (key.indexOf('radioValues') > -1) {
          radioSelectionsObj[key.split('_')[1]] = this.form[key]
        }

        // 多选框
        if (key.indexOf('checkbox') > -1) {
          info[key] = this.form[key];
          checkboxArr = checkboxArr.concat(this.form[key])
        }
      }

      let attr = {
        radioSelections: radioSelectionsObj,
        dropDown: dropDownMap,
        inputValues: inputValuesObj,
        checkbox: info,
        checkList: checkboxArr
      };
      // 数据组装
      this.form.attribute = attr;
      this.form.answer = JSON.stringify(attr);
      this.form.recycleNumber = this.form.orderNumber;

      this.$refs['form'].validate(valid => {
        if (valid) {
          recycleAndStorage(this.form).then(response => {
            this.$modal.msgSuccess('操作成功')
            this.show = false;
            this.$parent.getList();
          })
        }
      })
    },

    // 打开新增对话框
    handleOpen(row, t) {
      this.imgUrl = env;
      this.t = t;
      this.show = true;
      this.form = row;
      // 初始化
      this.init();
      this.$nextTick(() => {
        this.handleGameChange(this.form.dictCodeId);
      });
      this.$forceUpdate()
    },

    // 关闭
    handleClose() {
      this.show = false;
    },

    //选中分类事件
    changeChannel(value) {
      this.form.phoneId = null
      this.form.phoneCode = null
      this.bindingChannelList.forEach(item => {
        if (item.dictCode == value) {
          unboundPhonesByCategory(item.dictValue).then(res => {
            this.phoneList = res.data
            if (this.bindingChannelId == value) {
              this.phoneList.unshift(this.phoneData)
            }
          });
        }
      })
    },

    //选中手机事件
    changePhone(value) {
      this.phoneList.forEach(item => {
        if (item.phoneId == value) {
          this.form.phoneCode = item.phoneCode
          this.form.phoneId = item.phoneId
          this.form.phoneNumber = item.phoneNumber;
        }
      })
    },

    handleGameChange(dictCodeId) {
      // 游戏分类
      listDict({dictCodeId: dictCodeId}).then(response => {
        let data = response.data;
        let result = [];

        data.map(ii => {
          if (ii.gameKey === 'group') {
            this.regionalServers = ii.children;
          } else {
            result.push(ii);
          }
        });
        this.result = result;

        if (this.result.length > 0) {
          //处理多选框问题
          this.result.map((item, indx) => {
            if (item.fieldType == 'checkbox') {
              this.$set(this.form, 'checkbox_' + item.gameKey, new Array());
            }
          });

          // 其他赋值
          let bindingChannelId = ''
          let obj = {
            phoneCode: this.form.phoneCode,
            phoneId: this.form.phoneId,
            phoneNumber: this.form.phoneNumber
          };

          this.bindingChannelList.forEach(item => {
            if (item.dictValue == this.form.phoneField) {
              bindingChannelId = item.dictCode
            }
          });

          unboundPhonesByCategory(this.form.phoneField).then(res => {
            this.phoneList = res.data
            this.phoneData = obj
            if (!this.phoneList.find(item => item.phoneId == this.phoneData.phoneId)) {
              this.phoneList.unshift(this.phoneData)
            }
          });

          this.bindingChannelId = bindingChannelId;
          this.form.bindingChannelId = bindingChannelId;
          this.form.checkList = [];
          this.form.realNameId = Number(this.form.realNameId);
          this.form.dictCodeId = Number(this.form.dictCodeId);

          if (this.form.imagess == null) {
            this.form.imagess = [];
          }

          // 动态赋值
          if (this.form.id && this.form.answer) {
            // 解析
            let row = JSON.parse(this.form.answer);

            // 单选框 radio
            let radio = row.radioSelections;
            if (JSON.stringify(radio) != '{}') {
              for (var key in radio) {
                this.$set(this.form, 'radioValues_' + key, radio[key])
              }
            }

            // 单选框 select
            let dropDown = row.dropDown;
            if (JSON.stringify(dropDown) != '{}') {
              for (var key in dropDown) {
                this.$set(this.form, 'dropDown_' + key, dropDown[key])
              }
            }

            // 输入框 input
            let inputValues = row.inputValues;
            if (JSON.stringify(inputValues) != '{}') {
              for (var key in inputValues) {
                this.$set(this.form, 'inputValues_' + key, inputValues[key])
              }
            }

            // 多选checkbox
            let checkList = row.checkList;
            if (checkList && checkList.length > 0) {
              result.map(i => {
                if (i.fieldType == 'checkbox') {
                  this.$set(this.form, 'checkbox_' + i.gameKey, checkList);
                }
              });
            }
          }
        }
      });
    },

    copyPhone() {
      // 获取当前选中的手机号
      const phone = this.form.phoneNumber;
      if (phone) {
        const el = document.createElement('textarea');
        el.value = phone;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        // 通知用户已复制
        this.$message({
          message: '手机号已复制到剪贴板',
          type: 'success'
        });
      } else {
        this.$message.error('请先选择手机号！');
      }
    },

    // 初始化
    init() {
      //游戏种类
      this.getDicts('game_category').then(res => {
        this.gameList = res.data
      });

      // 绑定渠道
      this.getDicts('binding_channel').then(res => {
        this.bindingChannelList = res.data
      });

      //回收客服
      this.passPost('recycle').then(res => {
        this.recycleList = res.data
      })

      //查询换绑客服
      this.passPost('change').then(res => {
        this.changeList = res.data
      })

      //查询回收渠道字典
      this.getDicts('recycle_channel').then(res => {
        this.recycleChannelList = res.data
      })
    }
  }
}
</script>
<style lang="scss">
.dialog-wrapper {
  .dialog-con {
    max-height: 65vh;
    overflow-y: auto;

    p {
      font-size: 18px;
      font-weight: 400;
      color: rgba(17, 38, 60, 1);
      border-left: 3px solid rgba(84, 91, 245, 1);
      padding-left: 10px;
    }

    .el-dialog__title {
      border-left: 3px solid rgba(84, 91, 245, 1);
      padding-left: 8px;
    }

    .wrap_img {
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px dashed #c1c1c1;
      width: 100%;
      height: 90px;

      div {
        display: flex;
        justify-content: center;
        width: 100%;
        height: 100%;
      }

      ::v-deep.el-upload {
        width: 100%;
        height: 100%;
      }

      .avatar-uploader-icon {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
      }
    }

    .el-input__inner {
      width: 180px;
    }

    .el-textarea__inner {
      width: 810px;
    }

    .show-img {
      position: relative;
      display: flex;
      margin-right: 8px;
      height: 90px;

      .icon {
        position: absolute;
        top: -10px;
        right: -10px;
        font-size: 20px;
        z-index: 1;
        cursor: pointer;
      }
    }
  }
}
</style>
